package simulation;

import gameobject.Player;
import gameobject.Sprite;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;

/**
 * Observer that keeps track of sprites' collisions,
 * deaths, and key events.
 *
 */
/**
 * @author Volodymyr, Rex
 *
 */
public class Observer implements KeyListener {
    private Game myGameSimulation;
    private List<Sprite> mySprites;

    /**
     * Constructs an observer.
     * @param gameSimulation that will use this observer
     */
    public Observer (Game gameSimulation) {
        myGameSimulation = gameSimulation;
        mySprites = myGameSimulation.getSpriteList();
    }

    /**
     * Checks for game over or any sprite
     * collisions.
     */
    public void update() {
        synchronized (mySprites) {
            if (gameIsOver()) {
                myGameSimulation.gameOver();
            }
            for (int i = 0; i < mySprites.size(); i++) {
                Sprite s = mySprites.get(i);
                for (int j = i + 1; j < mySprites.size(); j++) {
                    if (overlap(s, mySprites.get(j))) {
                        collide(s, mySprites.get(j));
                    }
                }
            }
        }
    }

    /**
     * Modify to change what happens when two sprites collide.
     *
     * @param s
     * @param sprite
     */
    private void collide (Sprite s, Sprite other) {
        s.collide(other);
        other.collide(s);
    }

    /**
     * Modify this method to suit your gameover conditions.
     *
     * @return if the game is over
     */
    private boolean gameIsOver () {
        boolean gameOver = false;
        for (Sprite s : mySprites) {
            if (s instanceof Player) {
                gameOver = !s.isVisible();
                if (gameOver) {
                    break;
                }
            }
        }
        return gameOver;
    }

    private boolean overlap (Sprite first, Sprite second) {
        return first.getBounds().intersects(second.getBounds());
    }

    @Override
    public void keyTyped (KeyEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void keyPressed (KeyEvent e) {
        synchronized (mySprites) {
            for (Sprite s : mySprites) {
                s.handleKeyPressed(e);
            }
        }
    }

    @Override
    public void keyReleased (KeyEvent e) {
        synchronized (mySprites) {
            for (Sprite s : mySprites) {
                s.handleKeyReleased(e);
            }
        }
    }
}
